from sqlalchemy import inspect

from Project1.db.Global import engine, Base
from sqlalchemy.orm import sessionmaker
from Project1.entity.Tables import Person

def initialize():
    # Session = sessionmaker(bind=engine)
    # session = Session()
    #
    # if not engine.has_table(engine, 't_person'):
    #     Person.__table__.create(engine)
    #     print('创建表成功')
    #
    # session.close()

    Base.metadata.create_all(engine)
    print("所有表已创建（如果不存在）")

    pass

def addPerson():
    # 创建会话
    Session = sessionmaker(bind=engine)
    session = Session()
    # 创建用户
    pserson = Person(name='John Doe',age=24,email='john@example.com')
    session.add(pserson)

    session.commit()

def addPerson(name,age,email):
    # 创建会话
    Session = sessionmaker(bind=engine)
    session = Session()
    # 创建用户
    pserson = Person(name=name,age=age,email=email)
    session.add(pserson)
    session.commit()

def updatePerson(id,name,age,email):
    # 创建会话
    Session = sessionmaker(bind=engine)
    session = Session()
    # 查询用户
    person = session.query(Person).filter_by(id=id).first()
    # 更新用户
    person.name = name
    person.age = age
    person.email = email

    session.commit()

def deletePerson(id):
    # 创建会话
    Session = sessionmaker(bind=engine)
    session = Session()
    person = session.query(Person).filter_by(id=id).first()
    session.delete(person)
    session.commit()

def showPersons():
    # 创建会话
    Session = sessionmaker(bind=engine)
    session = Session()
    # 查询用户
    persons = session.query(Person).all()
    for person in persons:
        print(person.id,person.name,person.age,person.email)

def findPersonByPage(page,size):
    Session = sessionmaker(bind=engine)
    session = Session()
    persons = session.query(Person).limit(size).offset((page-1)*size).all()
    return persons


